#!/usr/bin/env python
# -*- coding: utf-8 -*-
import datetime
import random
import time

from flask import jsonify, request
from flask_restful import Resource

from utility.api_security import APISecurity
from utility.odoo_manager import OdooManager  # 操作odoo的单例
from utility.error_code import error_code  # 异常代码
from utility.message_manager import MessageBusManager
from event import event_type
from command import command
from utility import tools
from utility.app_security import AppSecurity
import logging


FORMAT = "%(asctime)s %(thread)d %(message)s"
logging.basicConfig(level=logging.INFO, format=FORMAT)
AppSecurity = AppSecurity()

class TemplateAddAPI(Resource):
    """
    新增模板管理
    :request: post
    :param tempType: 模板类型
    :param tempName: 模板名称
    :param tempValue: 模板内容
    :param type: 类型 2 用户模板
    :returns: json string
    """
    #@AppSecurity.public_verify()
    #@AppSecurity.token_verify()
    def post(self):
        try:
            odoo = OdooManager().get_instance()
            params = tools.get_params(request)
            # 参数校验
            req_params = ['tempType','tempValue','classifyId']
            vrf_res = tools.required_parame_verif(req_params,params)
            if  vrf_res['code'] != 0:
                return jsonify(vrf_res)
            # 新增模板管理
            data_ = {
                'temp_type': params.get('tempType'),
                'type': '2',
                'content': params.get('tempValue'),
                'classify_code': params.get('classifyId'),
                'code': str(round(time.time(), 0) + random.randint(1, 100000))
            }
            data_ = odoo.env['res.config.template'].create(data_)
            create_event = event_type.OperationLogEvent('新增模板管理', 'id:{}'.format(data_))
            message_bus = MessageBusManager().get_message_bus()
            message_bus.handle(create_event)  # 发布事件
            return jsonify({'code': 0, 'msg': 'success', 'data': {'id': data_}, 'success': True})
        except AttributeError as e:
            logging.exception(e)
            return jsonify({'code': 404, 'msg': error_code[404]})
        except Exception as e:
            logging.exception(e)
            return jsonify({'code': 100, 'msg': error_code[100]})

class TemplateUpdateAPI(Resource):
    """
    修改模板管理
    :request: put
    :param tempType: 模板类型
    :param tempName: 模板名称
    :param tempValue: 模板内容
    :param id: 模板内容id
    :returns: json string
    """
    #@AppSecurity.public_verify()
    #@AppSecurity.token_verify()
    def put(self):
        try:
            odoo = OdooManager().get_instance()
            params = request.json
            # 参数校验
            req_params = ['id','tempType','tempValue','classifyId']
            vrf_res = tools.required_parame_verif(req_params,params)
            if  vrf_res['code'] != 0:
                return jsonify(vrf_res)
            query_ = [('id', '=', params.get('id'))]
            res_config_template = odoo.env['res.config.template'].search(query_)
            if not res_config_template:
                return jsonify({'code': 40005, 'msg': error_code[40005]})
            # 修改模板管理
            data_ = {
                'type': params.get('2'),
                'temp_type': params.get('tempType'),
                'content': params.get('tempValue'),
                'classify_code': params.get('classifyId'),
                'code': str(round(time.time(), 0) + random.randint(1, 100000))
            }
            data_ = odoo.env['res.config.template'].write(res_config_template,data_)
            create_event = event_type.OperationLogEvent('修改模板管理', 'id:{}'.format(params.get('id')))
            message_bus = MessageBusManager().get_message_bus()
            message_bus.handle(create_event)  # 发布事件
            return jsonify({'code': 0, 'msg': 'success', 'data': {'id': data_}, 'success': True})
        except AttributeError as e:
            logging.exception(e)
            return jsonify({'code': 404, 'msg': error_code[404]})
        except Exception as e:
            logging.exception(e)
            return jsonify({'code': 100, 'msg': error_code[100]})

class TemplateDeleteAPI(Resource):
    """
    删除模板
    :request: get
    :param id: 模板内容id
    :returns: json string
    """
    def get(self):
        # token校验
        payload = APISecurity().verify_access_token()
        if not payload:
            return jsonify({'code': 901, 'msg': error_code[901]})
        odoo = OdooManager().get_instance()
        params = tools.get_params(request)
        res = odoo.env['res.config.template'].search([
            ('type', '=', '2'),
            ('id', '=', int(params.get('id'))),
            ('create_uid', '=', int(payload['aud']))
        ])
        if res:
            res = res.pop()
            flag = odoo.env['res.config.template'].unlink(res)
            return jsonify({
                'msg': 'success',
                'code': 0,
                'data': None
            })
        else:
            return jsonify({
                'msg': '档案已被删除，请刷新重试',
                'code': 1
            })

class TemplateQueryListAPI(Resource):
    """
    查询模板详情列表
    :request: post
    :param tempType: 模板类型
    :param classifyId: 分类名称
    :param type: 类型 NULL 全部 1 系统模板 2 用户模板
    :param userId: 用户ID
    :param isAsc: 排序方向 排序的方向,示例值(asc,desc)
    :param orderByColumn: 排序列
    :param pageNum: 当前页数
    :param pageSize: 分页大小
    :returns: json string
    """
    #@AppSecurity.public_verify()
    #@AppSecurity.token_verify()
    def post(self):
        try:
            # token校验
            payload = APISecurity().verify_access_token()
            if not payload:
                return jsonify({'code': 901, 'msg': error_code[901]})
            odoo = OdooManager().get_instance()
            params = tools.get_params(request)
            is_asc = params.get('isAsc') if params.get('isAsc', False) else 'asc'
            order_by_column = params.get('orderByColumn') if params.get('orderByColumn', False) else 'create_date'
            #  构造排序方式
            order_ = order_by_column+' '+ is_asc
            #  初始化页数,返回数据条数,偏移
            page = int(params.get('pageNum')) if params.get('pageNum', False) else 1
            pagesize = int(params.get('pageSize')) if params.get('pageSize', False) else 10
            offset = page * pagesize - pagesize
            #  构造查询条件
            query_ = []
            if params.get('tempType'):
                query_.append(('temp_type', '=', int(params.get('tempType'))))
            if params.get('classifyId'):
                query_.append(('classify_code', '=', params.get('classifyId')))
            if params.get('type') == '2':
                query_.append(('create_uid', '=', payload['aud']))
                query_.append(('type', '=', '2'))
            elif params.get('type') == '1':
                query_.append(('type', '=', '1'))
            fields = ['id','code','type','content','classify_code','create_uid']
            res_config_templates = odoo.env['res.config.template'].search_read(query_,fields,  offset = offset, limit = pagesize, order = order_)
            data_ = []
            for  res_config_template in res_config_templates:
                data_tmp={
                    'id': res_config_template['id'],
                    'classifyId': res_config_template['classify_code'],
                    'classify': res_config_template['classify_code'],
                    'tempName': res_config_template['classify_code'],
                    'tempType': res_config_template['type'],
                    'tempValue': res_config_template['content'],
                    'userId': res_config_template['create_uid'][0]
                }
                data_.append(data_tmp)
            return jsonify({'code': 0, 'msg': 'success', 'data': data_, 'success': True})
        except AttributeError as e:
            logging.exception(e)
            return jsonify({'code': 404, 'msg': error_code[404]})
        except Exception as e:
            logging.exception(e)
            return jsonify({'code': 100, 'msg': error_code[100]})
